
package net.swa.dewei.service.impl;

import java.math.BigDecimal;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import net.swa.dewei.beans.entity.Battery;
import net.swa.dewei.beans.entity.BatteryPrice;
import net.swa.dewei.beans.entity.PriceChangeLog;
import net.swa.dewei.service.ChangePriceService;
import net.swa.system.dao.HibernateDaoSupport;
import net.swa.util.BuzConst;
import net.swa.util.JsonResult;

@Service("changePriceService")
public class ChangePriceServiceImpl extends HibernateDaoSupport implements ChangePriceService
{
    private final Logger log = Logger.getLogger(ChangePriceServiceImpl.class);

    @Override
    public JsonResult<String> batchAddChangePrice(PriceChangeLog model)
    {
        JsonResult<String> json = new JsonResult<String>();
        json.setSuccess(false);
        json.setMessage("init");
        String sql = null;
        Session session = getCurrentSession();
        Query q = null;
        if ((model.getPrice() > 0) && (!StringUtils.isBlank(model.getPinPai())))
        {
            Battery b = null;
            if (!StringUtils.isBlank((model.getXingHao())))
            {
                //如果型号存在，则可以确定一种电池
                String hql = " from Battery where   pinPai=:pinPai and xingHao=:xingHao  ";
                q = session.createQuery(hql);
                q.setString("pinPai", model.getPinPai());
                q.setString("xingHao", model.getXingHao());
                List<Battery> list = q.list();
                if (null != list && list.size() > 0)
                {
                    if (1 == list.size())
                    {
                        b = list.get(0);
                    }
                    else
                    {
                        json.setMessage("该品牌该型号电池添加存在异常！");
                        return json;
                    }
                }
                else
                {
                    json.setMessage("不存在该品牌该型号电池！");
                    return json;
                }
            }
            else
            {
                json.setMessage("请确定电池型号！");
                return json;
            }
            if (null != b && null != b.getId())
            {
                if (!StringUtils.isBlank(model.getProvince()))
                {
                    if (!StringUtils.isBlank(model.getChangeType()))
                    {
                        if (BuzConst.PRICE_CHANGE_TYPE_PLUS.equals(model.getChangeType()))
                        {
                            sql = " update  BatteryPrice  set ourPrice =(ourPrice+:p) where  province=:province ";
                        }
                        else
                        {
                            sql = " update  BatteryPrice  set ourPrice =(ourPrice-:p) where  province=:province ";
                        }
                        if (!StringUtils.isBlank(model.getCity()))
                        {
                            sql += " and city=:city ";
                            if (!StringUtils.isBlank(model.getTown()))
                            {
                                sql += " and town=:town ";
                            }
                        }
                        sql += " and batteryId=:batteryId ";
                        q = session.createQuery(sql);
                        q.setDouble("p", model.getPrice());
                        q.setString("province", model.getProvince());
                        if (!StringUtils.isBlank(model.getCity()))
                        {
                            q.setString("city", model.getCity());
                            if (!StringUtils.isBlank(model.getTown()))
                            {
                                q.setString("town", model.getTown());
                            }
                        }
                        q.setLong("batteryId", b.getId());
                        int num = q.executeUpdate();
                        model.setNum(num);
                        model.setSqlStr(sql);
                        model.setType(BuzConst.PRICE_CHANGE_ZONE_PART);
                        session.save(model);
                        json.setSuccess(true);
                        json.setMessage("成功更新" + num + "条地区价格数据。");
                    }
                }
                else
                {
                    if (!StringUtils.isBlank(model.getChangeType()))
                    {

                        String sql2 = null;
                        if (BuzConst.PRICE_CHANGE_TYPE_PLUS.equals(model.getChangeType()))
                        {
                            sql = " update  BatteryPrice  set ourPrice =(ourPrice+:p) where  batteryId=:batteryId ";
                            sql2 = " update  Battery  set ourPrice =(ourPrice+:p) where  id=:batteryId ";
                        }
                        else
                        {
                            sql = " update  BatteryPrice  set ourPrice =(ourPrice-:p) where  batteryId=:batteryId";
                            sql2 = " update  Battery  set ourPrice =(ourPrice-:p) where  id=:batteryId ";
                        }
                        q = session.createQuery(sql);
                        q.setDouble("p", model.getPrice());
                        q.setLong("batteryId", b.getId());
                        int num = q.executeUpdate();
                        model.setNum(num);
                        model.setSqlStr(sql);
                        model.setType(BuzConst.PRICE_CHANGE_ZONE_PART);
                        session.save(model);

                        q = session.createQuery(sql2);
                        q.setDouble("p", model.getPrice());
                        q.setLong("batteryId", b.getId());
                        int num2 = q.executeUpdate();
                        PriceChangeLog m = new PriceChangeLog();
                        BeanUtils.copyProperties(model, m);
                        m.setId(null);
                        m.setNum(num2);
                        m.setSqlStr(sql2);
                        m.setType(BuzConst.PRICE_CHANGE_ZONE_ALL);
                        session.save(m);
                        json.setSuccess(true);
                        json.setMessage("成功更新" + num + "条地区价格数据和" + num2 + "条统一价格数据。");
                    }
                    log.debug("没有选择省则是修改统一价格和自定义价格。。。");
                }
            }
            else
            {
                json.setSuccess(false);
                json.setMessage("error,系统出错。");
                log.debug("error,系统出错，该种错误不应该出现。");
            }
        }
        else
        {
            log.debug("价格调整值不合法or品牌型号不合法");
            json.setMessage("价格调整值或品牌型号不合法");
        }
        return json;
    }

    @Override
    public JsonResult<String> addChangePrice(PriceChangeLog model)
    {
        JsonResult<String> json = new JsonResult<String>();
        json.setSuccess(false);
        json.setMessage("init");
        String sql = null;
        Session session = getCurrentSession();
        Query q = null;

        if ((model.getPrice() > 0) && (!StringUtils.isBlank(model.getPinPai())))
        {
            Battery b = null;
            if (!StringUtils.isBlank((model.getXingHao())))
            {
                //如果型号存在，则可以确定一种电池
                String hql = " from Battery where   pinPai=:pinPai and xingHao=:xingHao  ";
                q = session.createQuery(hql);
                q.setString("pinPai", model.getPinPai());
                q.setString("xingHao", model.getXingHao());
                List<Battery> list = q.list();
                if (null != list && list.size() > 0)
                {
                    if (1 == list.size())
                    {
                        b = list.get(0);
                    }
                    else
                    {
                        json.setMessage("该品牌该型号电池添加存在异常！");
                        return json;
                    }
                }
                else
                {
                    json.setMessage("不存在该品牌该型号电池！");
                    return json;
                }
            }
            else
            {
                json.setMessage("请确定电池型号！");
                return json;
            }
            if (null != b && null != b.getId())
            {
                if (!StringUtils.isBlank(model.getProvince()))
                {
                    if (!StringUtils.isBlank(model.getChangeType()))
                    {
                        if (BuzConst.PRICE_CHANGE_TYPE_PLUS.equals(model.getChangeType()))
                        {
                            sql = " update  BatteryPrice  set ourPrice =(ourPrice+:p) where  province=:province ";
                        }
                        else
                        {
                            sql = " from  BatteryPrice  where  province=:province ";
                        }
                        if (!StringUtils.isBlank(model.getCity()))
                        {
                            sql += " and city=:city ";
                            if (!StringUtils.isBlank(model.getTown()))
                            {
                                sql += " and town=:town ";
                            }
                        }
                        sql += " and batteryId=:batteryId ";
                        q = session.createQuery(sql);
                        q.setString("province", model.getProvince());
                        if (!StringUtils.isBlank(model.getCity()))
                        {
                            q.setString("city", model.getCity());
                            if (!StringUtils.isBlank(model.getTown()))
                            {
                                q.setString("town", model.getTown());
                            }
                        }
                        q.setLong("batteryId", b.getId());
                        int num = 0;
                        if (BuzConst.PRICE_CHANGE_TYPE_PLUS.equals(model.getChangeType()))
                        {
                            q.setDouble("p", model.getPrice());
                            num = q.executeUpdate();
                            model.setNum(num);
                            model.setSqlStr(sql);
                            model.setType(BuzConst.PRICE_CHANGE_ZONE_PART);
                            session.save(model);
                            json.setSuccess(true);
                            json.setMessage("涨价成功，更新" + num + "条地区价格数据。");
                        }
                        else
                        {
                            List<BatteryPrice> pl = q.list();
                            if (null != pl && pl.size() > 0)
                            {
                                for (BatteryPrice p : pl)
                                {
                                    if (null != p.getOurPrice())
                                    {
                                        double d = Double.parseDouble(p.getOurPrice());
                                        if (d > model.getPrice())
                                        {
                                            p.setOurPrice(subtract(d, model.getPrice()));
                                            session.save(p);
                                            num++;
                                        }
                                        else
                                        {
                                            json.setSuccess(false);
                                            json.setMessage("如此降价就赔钱了！");
                                            return json;
                                        }
                                    }
                                }
                            }
                            model.setNum(num);
                            model.setSqlStr("");
                            model.setType(BuzConst.PRICE_CHANGE_ZONE_PART);
                            session.save(model);
                            json.setSuccess(true);
                            json.setMessage("减价成功，更新" + num + "条地区价格数据。");
                        }
                    }
                }
                else
                {
                    if (!StringUtils.isBlank(model.getChangeType()))
                    {
                        String sql2 = null;
                        int num = 0;
                        if (BuzConst.PRICE_CHANGE_TYPE_PLUS.equals(model.getChangeType()))
                        {
                            sql = " update  BatteryPrice  set ourPrice =(ourPrice+:p) where  batteryId=:batteryId ";
                            sql2 = " update  Battery  set ourPrice =(ourPrice+:p) where  id=:batteryId ";
                        }
                        else
                        {
                            sql = " from  BatteryPrice  where  batteryId=:batteryId ";
                        }
                        q = session.createQuery(sql);
                        q.setLong("batteryId", b.getId());
                        if (BuzConst.PRICE_CHANGE_TYPE_PLUS.equals(model.getChangeType()))
                        {

                            q.setDouble("p", model.getPrice());
                            num = q.executeUpdate();
                            model.setNum(num);
                            model.setSqlStr(sql);
                            model.setType(BuzConst.PRICE_CHANGE_ZONE_PART);
                            session.save(model);
                            q = session.createQuery(sql2);
                            q.setDouble("p", model.getPrice());
                            q.setLong("batteryId", b.getId());
                            int num2 = q.executeUpdate();
                            PriceChangeLog m = new PriceChangeLog();
                            BeanUtils.copyProperties(model, m);
                            m.setId(null);
                            m.setNum(num2);
                            m.setSqlStr(sql2);
                            m.setType(BuzConst.PRICE_CHANGE_ZONE_ALL);
                            session.save(m);
                            json.setSuccess(true);
                            json.setMessage("成功更新" + num + "条地区价格数据和" + num2 + "条统一价格数据。");
                        }
                        else
                        {
                            List<BatteryPrice> pl = q.list();
                            if (null != pl && pl.size() > 0)
                            {
                                for (BatteryPrice p : pl)
                                {
                                    if (null != p.getOurPrice())
                                    {
                                        double d = Double.parseDouble(p.getOurPrice());
                                        if (d > model.getPrice())
                                        {
                                            p.setOurPrice(subtract(d, model.getPrice()));
                                            session.save(p);
                                            num++;
                                        }
                                        else
                                        {
                                            json.setSuccess(false);
                                            json.setMessage("如此降价您就赔钱了！");
                                            return json;
                                        }
                                    }
                                }
                            }
                            double d = Double.parseDouble(b.getOurPrice());
                            if (d > model.getPrice())
                            {
                                b.setOurPrice(subtract(d, model.getPrice()));
                                session.save(b);

                                model.setNum(num);
                                model.setSqlStr("");
                                model.setType(BuzConst.PRICE_CHANGE_ZONE_PART);
                                session.save(model);

                                PriceChangeLog m = new PriceChangeLog();
                                BeanUtils.copyProperties(model, m);
                                m.setId(null);
                                m.setNum(1);
                                m.setSqlStr(sql2);
                                m.setType(BuzConst.PRICE_CHANGE_ZONE_ALL);
                                session.save(m);
                                json.setSuccess(true);
                                json.setMessage("成功更新" + num + "条地区价格数据和1条统一价格数据。");
                            }
                            else
                            {
                                json.setSuccess(false);
                                json.setMessage("如此降价就赔钱了！");
                                return json;
                            }
                            json.setSuccess(true);
                        }
                    }
                    log.debug("没有选择省则是修改统一价格和自定义价格。。。");
                }
            }
            else
            {
                json.setSuccess(false);
                json.setMessage("error,系统出错。");
                log.debug("error,系统出错，该种错误不应该出现。");
            }
        }
        else
        {
            log.debug("价格调整值不合法or品牌型号不合法");
            json.setMessage("调整价格要大于0，且该品牌电池存在");
        }
        return json;
    }

    private String subtract(double v1 , double v2)
    {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.subtract(b2).doubleValue() + "";
    }
}